/************************************************************************************/
/*  Program name CAPFNDIMP_REQUEST_SETS.sql                                         */
/*  Creater:  Chan Billy Ka Keung (PCCW - UniHub)                                   */
/*************   History   *************************                                */
/* 01 FEB, 2006   CHAN Billy Ka Keung         First created                         */
/************************************************************************************/

SET SERVEROUTPUT ON SIZE 1000000;

DECLARE

	lv_Prog_ID		VARCHAR2(100) 	:=	'CAPFNDIMP_OPERATING_UNITS';

	lv_Scc_Count	NUMBER			:=	0;
	lv_Err_Count	NUMBER			:=	0;
	lv_Err_Msg		VARCHAR2(500)	:=	'No Error';
	
	lv_NewLE		VARCHAR2(100);

	CURSOR Cur_F IS
	SELECT
		*
	FROM
		CRST_FND_OPERATING_UNITS;

BEGIN
	
		SELECT	Distinct(A.ORGANIZATION_ID)
		INTO	lv_NewLE
		FROM	HR_ORGANIZATION_INFORMATION A, GL_SETS_OF_BOOKS B
		WHERE	A.ORG_INFORMATION1 = TO_CHAR(B.SET_OF_BOOKS_ID)
		AND SUBSTR(B.SHORT_NAME,5,4) IN (SELECT DISTINCT(SUBSTR(NAME,4,4)) FROM CRST_FND_OPERATING_UNITS);
		
	UPDATE
		HR_OPERATING_UNITS A
	SET
		A.NAME	=  CAPBRIMP_MAPPING.GetOUMapping(A.NAME)
	WHERE
		BUSINESS_GROUP_ID 	IN (SELECT BUSINESS_GROUP_ID
							FROM CRST_FND_ORG_UNITS_MAP);
	

	FOR C1 IN Cur_F LOOP
		BEGIN

			INSERT INTO HR_OPERATING_UNITS
			VALUES
			(
			CAPBRIMP_MAPPING.GetBGMapping(C1.BUSINESS_GROUP_ID),
			CAPBRIMP_MAPPING.GetOrgMapping(C1.ORGANIZATION_ID),
			C1.NAME,
			C1.DATE_FROM,
			C1.DATE_TO,
			lv_NewLE,
			CAPBRIMP_MAPPING.GetSOBIDMapping(C1.SET_OF_BOOKS_ID)
			);
		EXCEPTION
			WHEN OTHERS THEN
				DBMS_OUTPUT.Put_Line(SQLERRM);
				lv_Err_Count	:=	lv_Err_Count + 1;
		END;
		lv_Scc_Count		:= lv_Scc_Count + 1;
	END LOOP;

	IF lv_Err_Count	>	0	THEN
		ROLLBACK;
	END IF;

	INSERT INTO CAPCNV_LOG(
		PROG_ID,
		PROCESS_DATE,
		RECORD_PROCESSED,
		RECORD_REJECTED,
		RECORD_EXTRACTED,
		ERR_MSG
		)
	VALUES (
		lv_Prog_ID,
		SYSDATE,
		lv_Scc_Count,
		lv_Err_Count,
		lv_Scc_Count - lv_Err_Count,
		lv_Err_Msg
	);

	COMMIT;
END;
/